document.addEventListener('DOMContentLoaded', function () {
  const iframe = document.getElementById('previewFrame')
  const htmlEditor = document.getElementById('html-content')
  const cssEditor = document.getElementById('css-content')
  const jsEditor = document.getElementById('js-content')
  const panelsContainer = document.querySelector('.panels-container')
  const iframeContainer = document.querySelector('.iframe-container')

  let isResizing = false
  let debounceTimer

  // 初始化所有垂直拖拽条的功能
  const initVerticalResizers = () => {
    const resizers = document.querySelectorAll('.resizer-vertical')
    resizers.forEach(resizer => {
      resizer.addEventListener('mousedown', function (e) {
        e.preventDefault()
        isResizing = true
        document.body.style.cursor = 'col-resize'
        iframe.style.pointerEvents = 'none'

        const prevPanel = this.previousElementSibling
        const nextPanel = this.nextElementSibling
        const containerWidth = panelsContainer.offsetWidth
        const startX = e.clientX
        const prevPanelPercent = (prevPanel.offsetWidth / containerWidth) * 100
        const nextPanelPercent = (nextPanel.offsetWidth / containerWidth) * 100

        const handleMouseMove = e => {
          if (!isResizing) return
          const dx = ((e.clientX - startX) / containerWidth) * 100
          const newPrevPanelPercent = prevPanelPercent + dx
          const newNextPanelPercent = nextPanelPercent - dx
          const minPercent = 15 // 最小宽度百分比

          if (newPrevPanelPercent >= minPercent && newNextPanelPercent >= minPercent) {
            prevPanel.style.flex = `0 0 ${newPrevPanelPercent}%`
            nextPanel.style.flex = `0 0 ${newNextPanelPercent}%`
          }
        }

        const handleMouseUp = () => {
          isResizing = false
          document.body.style.cursor = ''
          iframe.style.pointerEvents = 'auto'
          document.removeEventListener('mousemove', handleMouseMove)
          document.removeEventListener('mouseup', handleMouseUp)
        }

        document.addEventListener('mousemove', handleMouseMove)
        document.addEventListener('mouseup', handleMouseUp)
      })
    })
  }

  // 初始化水平拖拽条的功能
  const initHorizontalResizer = () => {
    const resizer = document.querySelector('.resizer-horizontal')
    resizer.addEventListener('mousedown', function (e) {
      e.preventDefault()
      isResizing = true
      document.body.style.cursor = 'row-resize'
      iframe.style.pointerEvents = 'none'

      const containerHeight = document.querySelector('.container').offsetHeight
      const startY = e.clientY
      const topPanelPercent = (panelsContainer.offsetHeight / containerHeight) * 100
      const bottomPanelPercent = (iframeContainer.offsetHeight / containerHeight) * 100

      const handleMouseMove = e => {
        if (!isResizing) return
        const dy = ((e.clientY - startY) / containerHeight) * 100
        const newTopPercent = topPanelPercent + dy
        const newBottomPercent = bottomPanelPercent - dy
        const minPercent = 15 // 最小高度百分比

        if (newTopPercent >= minPercent && newBottomPercent >= minPercent) {
          panelsContainer.style.flex = `0 0 ${newTopPercent}%`
          iframeContainer.style.flex = `0 0 ${newBottomPercent}%`
        }
      }

      const handleMouseUp = () => {
        isResizing = false
        document.body.style.cursor = ''
        iframe.style.pointerEvents = 'auto'
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
      }

      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)
    })
  }

  // 根据 textarea 的内容更新行号显示
  const updateLineNumbers = editorElement => {
    const lineNumbersContainer = editorElement.parentElement.querySelector('.line-numbers')
    const lineCount = editorElement.value.split('\n').length
    //注意,这里使用这个是因为textarea会保留内容的换行符号,而一般其他的不会保留换行符号
    const lines = Array.from({length: lineCount}, (_, i) => i + 1).join('\n')
    lineNumbersContainer.innerText = lines
  }

  // 初始化所有编辑器的事件监听
  const initContentListeners = () => {
    const editors = document.querySelectorAll('.panel-content')
    editors.forEach(editor => {
      const lineNumbers = editor.parentElement.querySelector('.line-numbers')
      updateLineNumbers(editor)

      editor.addEventListener('input', () => {
        updateIframe()
        updateLineNumbers(editor)
      })

      editor.addEventListener('scroll', () => {
        lineNumbers.scrollTop = editor.scrollTop
      })

      editor.addEventListener('keydown', function (e) {
        if (e.key === 'Tab') {
          e.preventDefault()
          const start = this.selectionStart
          const end = this.selectionEnd
          this.value = this.value.substring(0, start) + '  ' + this.value.substring(end)
          this.selectionStart = this.selectionEnd = start + 2
        }
      })
    })
  }

  // 更新 iframe 预览内容
  const updateIframe = () => {
    clearTimeout(debounceTimer)
    debounceTimer = setTimeout(() => {
      const htmlCode = htmlEditor.value
      const cssCode = cssEditor.value
      const jsCode = jsEditor.value

      const srcDocContent = `
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>${cssCode}</style>
        </head>
        <body>
            ${htmlCode}
            <script>
              try {
                ${jsCode}
              } catch (err) {
                console.error("JavaScript Error In Preview:", err);
              }
            <\/script>
        </body>
        </html>
      `
      iframe.srcdoc = srcDocContent
    }, 300)
  }

  // 初始化所有功能
  const initialize = () => {
    // 设置初始布局比例
    panelsContainer.style.flex = '0 0 60%'
    iframeContainer.style.flex = '1 0 40%'

    document.querySelectorAll('.panel').forEach((panel, index) => {
      panel.style.flex = `0 0 ${100 / 3}%`
    })

    initVerticalResizers()
    initHorizontalResizer()
    initContentListeners()
    updateIframe()
  }

  initialize()
})
